import {
  inStorePageApi,
  addInStoreApi,
  editInStoreApi,
  delInStoreApi,
  getAssetDetailApi
} from '@/api/asset-management/asset-in-store'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { InStoreModel } from '@/api/model/asset-management/asset-in-store-model'
import dayjs from 'dayjs'
import getUserInfo from '@/hooks/getUserInfo'
import { groupBy } from 'lodash-es'

type Props = {
  handleType: Ref<'add' | 'edit' | ''>
  handleTag: Ref<string>
  inStoreModalShow: Ref<boolean>
  inStoreForm: Ref<Partial<InStoreModel>>
  inStoreItemForm: Ref<Partial<InStoreModel>>
  proTableInst: Ref<ProTableInst | null>
  typeListLength: Ref<number>
  purchaseLoading: Ref<boolean>
  purchaseOptions: Ref<any>
  purchaseDetail: Ref<any>
}

export const useInStoreApi = ({
  handleType,
  handleTag,
  inStoreModalShow,
  inStoreForm,
  proTableInst,
  typeListLength,
  inStoreItemForm,
  purchaseLoading,
  purchaseOptions,
  purchaseDetail
}: Props) => {
  const confirmLoading = ref(false)

  const { userInfo } = getUserInfo()

  // 获取入库列表
  const fetchInStorePage = async (
    pageRequest: PageRequest,
    queryParams: InStoreModel
  ) => {
    const res = await inStorePageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改入库
  const fetchAddOrEditInStore = async () => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addInStoreApi : editInStoreApi
    const assetList: any[] = []
    let inStoreNumber = 0
    for (let i = 0; i < typeListLength.value; i++) {
      const asset: any = {}
      Object.keys(inStoreItemForm.value).forEach((key) => {
        const index = key.replace(/[^\d]/g, '')
        console.log('index', index, i.toString())

        if (index == i.toString()) {
          const property = key.replace(/[0-9]/g, '')
          if (property === 'typeId' || property === 'warehouseId') {
            asset[property] = parseInt(inStoreItemForm.value[key])
          } else {
            asset[property] = inStoreItemForm.value[key]
          }
          // 总入库数量
          if (property === 'number') {
            inStoreNumber += inStoreItemForm.value[key] as number
          }
        }
      })
      // 部门id
      asset.branchId = purchaseDetail.value.purchaseBranch
      assetList.push(asset)
    }
    if (inStoreNumber > purchaseDetail.value.number) {
      confirmLoading.value = false
      return useMsg(
        'warning',
        '入库资产总数不能大于采购资产总数，采购资产总数为' +
          purchaseDetail.value.number
      )
    }
    const data = {
      ...inStoreForm.value,
      inStoreType: '0',
      inStoreDate: dayjs().format('YYYY-MM-DD'),
      purchaseName: useDictDisplay(
        purchaseOptions.value,
        inStoreForm.value.purchaseId
      ),
      branchId: purchaseDetail.value.purchaseBranchId,
      branchName: purchaseDetail.value.purchaseBranch,
      inStoreNumber,
      assetList
    }
    const res = await fetch(data)
    if (res.code === '0000') {
      useMsg('success', handleTag.value + '成功')
      proTableInst.value?.reload()
      inStoreModalShow.value = false
    }
    confirmLoading.value = false
  }

  // 删除入库
  const fetchDelInStore = async (id) => {
    const res = await delInStoreApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  const fetchGetAssetDetail = async (id) => {
    const res = await getAssetDetailApi({ id })
    if (res.code === '0000') {
      const groupAssetObj = groupBy(res.data.assetList, 'assetName')
      typeListLength.value = Object.keys(groupAssetObj).length
      const tempFormItemData = {}
      Object.keys(groupAssetObj).forEach((assetType, index) => {
        const groupAsset = groupAssetObj[assetType][0]
        Object.keys(groupAsset).forEach((key) => {
          if (key === 'warehouseId' || key === 'typeId') {
            tempFormItemData[key + index] = groupAsset[key].toString()
          } else {
            tempFormItemData[key + index] = groupAsset[key]
          }
        })
        tempFormItemData['number' + index] = groupAssetObj[assetType].length
      })
      inStoreItemForm.value = tempFormItemData

      inStoreForm.value = Object.assign({}, res.data, {
        purchaseId: res.data.purchaseId?.toString() || null
      })
    }
  }

  return {
    fetchInStorePage,
    fetchAddOrEditInStore,
    fetchGetAssetDetail,
    fetchDelInStore,
    confirmLoading
  }
}
